package com.origin.ebuy.forg.web.controller.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.origin.ebuy.bargd.service.user.IUserService;
import com.origin.ebuy.bargd.service.user.impl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("uname");
		String passwd = request.getParameter("passwd");
		IUserService service = new UserServiceImpl();
		
		try {
			JSONObject jsonObject = service.userLogin(name, passwd);
			//用户是否有效
			int state = jsonObject.getIntValue("state");
				//登陆失败
				if(jsonObject.isEmpty()){
					response.sendRedirect("login.jsp?type=0");
				//用户登陆成功	
				}else{
					if(state == 0){
						//当前用户不可用
						response.sendRedirect("login.jsp?type=-2");
					}else{
						//保存用户id
						HttpSession session = request.getSession();
						session.setAttribute("uid", jsonObject.getString("id"));
						
						//根据不同角色进行跳转	
						int rule = jsonObject.getIntValue("rule");
						if(rule == 1){
							response.sendRedirect("admin.jsp");
						}else{
							response.sendRedirect("main.jsp");
						}
					}
				}
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendRedirect("login.jsp?type=-1");
		}
	}

}
